﻿using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using SW.DDD.Domain;
using SW.DDD.Infrastructure;

namespace SW.DDD.Application.Query
{
    /// <summary>
    /// 查找处理类
    /// </summary>
    /// <typeparam name="TView">要返回的视图类型</typeparam>
    /// <typeparam name="TEntity">来源实体类型</typeparam>
    /// <typeparam name="TKey">实体键</typeparam>
    public class FindHandler<TView, TEntity, TKey> : IQueryHandler<Find<TView, TEntity, TKey>, TView>
        where TEntity : class, IAggregateRoot<TKey>
        where TKey : notnull
    {
        protected IRepository<TEntity, TKey> Repository { get; }

        protected IMapper Mapper { get; }

        public FindHandler(IRepository<TEntity, TKey> repository, IMapper mapper)
        {
            Repository = repository;
            Mapper = mapper;
        }

        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<TView> Handle(Find<TView, TEntity, TKey> request, CancellationToken cancellationToken)
        {
            var data = await Repository.QueryAsync(qy =>
                Mapper.ProjectTo<TView>(qy.Where(e => e.Id.Equals(request.Id)), request.Parameters)
            );
            return data.FirstOrDefault() ?? throw new EntityNotFoundException(typeof(TEntity), request.Id);
        }
    }
}
